package xyz.naoyu.servlets.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import xyz.naoyu.dao.BaseDao;
import xyz.naoyu.entity.User;
import xyz.naoyu.servlets.service.UserService;
import xyz.naoyu.settings;
import xyz.naoyu.utils.jbcrypt.BCrypt;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author yWieLoc
 * @date 2022/3/16 17:48
 */

@WebServlet("/api/user")
public class UserServlet extends BaseServlet implements UserService {



    /**
     * 用户存在检测
     * @param req
     * @param resp
     */
    @Override
    public void userExactCheck(HttpServletRequest req, HttpServletResponse resp) {
        BaseDao tools = new BaseDao();      // 连接工具
        User user = new User(req.getParameter("UId"));

        try {
            user = (User) user.getInfo(tools);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                resp.getWriter().append(JSON.toJSONString(
                        new BackCode(false,"用户UID查询无果",null)
                ));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            return;
        }
    }

    /**
     * 用户登录密码验证
     * @param req
     * @param resp
     */
    @Override
    public void userLogin(HttpServletRequest req, HttpServletResponse resp) {
        BaseDao tools = new BaseDao();      // 连接工具
        User user = new User(req.getParameter("UId"));


        try {
            user = (User) user.getInfo(tools);
            if( BCrypt.checkpw( req.getParameter("passWord"), user.getPassWord())) {
                // TODO: 2022/3/18 登录成功
                HttpSession session = req.getSession();

                // 设置标识
                session.setAttribute("Id",user.getId());



                resp.getWriter().append(JSON.toJSONString(
                        new BackCode(true,"登录成功",null)
                ));

            } else {
                resp.getWriter().append(JSON.toJSONString(
                        new BackCode(false,"用户密码不正确",null)
                ));

            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                resp.getWriter().append(JSON.toJSONString(
                        new BackCode(false,"用户UID不存在",null)
                ));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

    }

    /**
     * 用户信息更新
     * @param req
     * @param resp
     */
    @Override
    public void edit(HttpServletRequest req, HttpServletResponse resp) {
        BaseDao tools = new BaseDao();      // 连接工具
        User user = new User(req.getParameter("Id"));

        // TODO: 2022/3/19 需重构
        try {
            user = (User) user.getInfo((tools));

            // 新建
            if(user.getCreateTime() == null) {
                // 注册
                System.out.println(req.getParameter("user"));


                user.setCreatorId((String) req.getSession().getAttribute("Id"));
                user.setCreateTime(String.valueOf(System.currentTimeMillis()));



            } else {

                // 编辑 不是同一人
                if( user.getCreatorId() != req.getSession().getAttribute("Id") ) {
                    resp.getWriter().append(JSON.toJSONString(
                            new BackCode(false,"没有权限",user.getId())
                    ));
                    return;
                }

                // 加载参数
                user = (User) JSON.parse(req.getParameter("user"));
            }




            user.setCreatorId(user.getId());
            user.setType("User");
            // 传向后端
            if(user.infoUpdate(tools)==0) {
                resp.getWriter().append(JSON.toJSONString(
                        new BackCode(false,"更新失败",user.getId())
                ));
                return;
            } else {
                resp.getWriter().append(JSON.toJSONString(
                        new BackCode(true,"更新成功",user.getId())
                ));
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("注册失败");
        }
    }


    @Override
    public void show(HttpServletRequest req, HttpServletResponse resp) {
        BaseDao tools = new BaseDao();      // 连接工具
        User user = new User(req.getParameter("Id"));

        try {
            user = (User) user.getInfo(tools);
            HttpSession session=req.getSession();

            // id不同
            if (session.getAttribute("UId")!=user.getId())  user.InfoLimit();
            // 账户锁定展示 null
            if(user.getState() == null || user.getState() == settings.state.getString("LOCK"))
                user = null;

            resp.getWriter().append(JSON.toJSONString(
                    new BackCode(true,null, JSON.toJSONString(user))
            ));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void del(HttpServletRequest req, HttpServletResponse resp) {
        BaseDao tools = new BaseDao();      // 连接工具
        User user = new User((String) req.getSession().getAttribute("Id"));



        try {

            // 密码校验
            if( !BCrypt.checkpw( req.getParameter("passWord"), user.getPassWord()) ) {
                resp.getWriter().append(JSON.toJSONString(
                        new BackCode(false, "注销失败,密码错误",null)
                ));
            }


            if (user.delSelf(tools)) {
                resp.getWriter().append(JSON.toJSONString(
                        new BackCode(true, "注销成功",null)
                ));
            } else {
                resp.getWriter().append(JSON.toJSONString(
                        new BackCode(false, "注销失败",null)
                ));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
